<template>
    <div class="authority-manage">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-left">
                <h2>角色权限管理</h2>
                <p class="header-desc">为角色配置菜单访问权限</p>
            </div>
            <div class="header-right" v-if="currentRole.id">
                <el-button type="primary" @click="savePermissions" :loading="saving">
                    保存权限配置
                </el-button>
                <el-button @click="resetPermissions">重置</el-button>
            </div>
        </div>

        <div class="authority-content">
            <!-- 角色选择区域 -->
            <div class="role-selection-card">
                <div class="card-header">
                    <h3>选择角色</h3>
                    <span class="role-count">共 {{ roleList.length }} 个角色</span>
                </div>
                <div class="card-body">
                    <div class="role-list">
                        <div 
                            v-for="role in roleList" 
                            :key="role.id"
                            class="role-item"
                            :class="{ 'active': currentRole.id === role.id }"
                            @click="selectRole(role)">
                            <div class="role-info">
                                <div class="role-name">{{ role.name }}</div>
                                <div class="role-desc">{{ role.description || '暂无描述' }}</div>
                            </div>
                            <div class="role-status">
                                <el-tag :type="role.status ? 'success' : 'danger'" size="small">
                                    {{ role.status ? '启用' : '禁用' }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 权限配置区域 -->
            <div class="permissions-config" v-if="currentRole.id">
                <!-- 当前角色信息 -->
                <div class="current-role-card">
                    <div class="card-header">
                        <h3>当前配置角色</h3>
                    </div>
                    <div class="card-body">
                        <div class="role-detail">
                            <div class="role-avatar">📋</div>
                            <div class="role-detail-info">
                                <h4>{{ currentRole.name }}</h4>
                                <p>{{ currentRole.description || '暂无描述' }}</p>
                                <div class="role-meta">
                                    <span>权限字符: {{ currentRole.key || '未设置' }}</span>
                                    <span>创建时间: {{ currentRole.create_time }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 菜单权限配置 -->
                <div class="menu-permissions-card">
                    <div class="card-header">
                        <h3>菜单访问权限</h3>
                        <div class="header-actions">
                            <el-button size="small" @click="checkAllMenus">全选</el-button>
                            <el-button size="small" @click="uncheckAllMenus">取消全选</el-button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="menu-tree-container">
                            <el-tree
                                ref="menuTree"
                                :data="menuOptions"
                                show-checkbox
                                node-key="id"
                                :default-checked-keys="menuCheckedKeys"
                                :props="{ label: 'name', children: 'children' }"
                                :check-strictly="false"
                                class="menu-tree">
                                <template #default="{ node, data }">
                                    <div class="menu-node">
                                        <span class="menu-name">{{ data.name }}</span>
                                        <el-tag v-if="data.path" size="small" class="menu-path">{{ data.path }}</el-tag>
                                    </div>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
                <div class="empty-content">
                    <div class="empty-icon">👤</div>
                    <h3>请选择一个角色开始配置权限</h3>
                    <p>从左侧角色列表中选择要配置权限的角色</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { apiSystemRole, apiSystemRoleIdToMenuid, apiPermissionSave } from '@/api/api'

export default {
    name: "authorityManage",
    data() {
        return {
            roleList: [],
            currentRole: {},
            menuOptions: [],
            menuCheckedKeys: [],
            saving: false,
            loading: false
        }
    },
    created() {
        this.init()
    },
    watch: {
        // 监听路由参数变化
        '$route.query.id': {
            handler(newRoleId) {
                if (newRoleId && this.roleList.length > 0) {
                    const role = this.roleList.find(r => r.id == newRoleId)
                    if (role) {
                        this.selectRole(role)
                    }
                }
            },
            immediate: false
        }
    },
    methods: {
        async init() {
            this.loading = true
            try {
                await this.loadRoles()
                
                // 如果URL中有角色ID，自动选择该角色
                const roleId = this.$route.query?.id
                if (roleId) {
                    const role = this.roleList.find(r => r.id == roleId)
                    if (role) {
                        await this.selectRole(role)
                    }
                }
            } finally {
                this.loading = false
            }
        },

        // 加载角色列表
        async loadRoles() {
            const res = await apiSystemRole({ page: 1, limit: 999 })
            if (res.code === 200) {
                this.roleList = res.data.list || res.data || []
            }
        },

        // 选择角色
        async selectRole(role) {
            this.currentRole = { ...role }
            
            // 加载角色的菜单权限
            await this.loadRoleMenus(role.id)
        },

        // 加载角色菜单权限
        async loadRoleMenus(roleId) {
            const res = await apiSystemRoleIdToMenuid(roleId)
            if (res.code === 200) {
                const data = res.data
                if (data.menu_tree) {
                    this.menuOptions = this.processMenuTree(data.menu_tree)
                    this.menuCheckedKeys = data.role_menu_ids || []
                }
            }
        },

        // 处理菜单树数据，简化为只有基本信息
        processMenuTree(menuTree) {
            return menuTree.map(menu => ({
                id: menu.id,
                name: menu.name,
                path: menu.path,
                children: menu.children ? this.processMenuTree(menu.children) : []
            }))
        },

        // 全选菜单
        checkAllMenus() {
            const allKeys = this.getAllMenuKeys(this.menuOptions)
            this.$refs.menuTree.setCheckedKeys(allKeys)
        },

        // 取消全选菜单
        uncheckAllMenus() {
            this.$refs.menuTree.setCheckedKeys([])
        },

        // 获取所有菜单ID
        getAllMenuKeys(menus) {
            let keys = []
            menus.forEach(menu => {
                keys.push(menu.id)
                if (menu.children) {
                    keys = keys.concat(this.getAllMenuKeys(menu.children))
                }
            })
            return keys
        },

        // 保存权限配置
        async savePermissions() {
            if (!this.currentRole.id) {
                this.$message.warning('请先选择角色')
                return
            }

            this.saving = true
            try {
                // 获取选中的菜单
                const checkedMenus = this.$refs.menuTree.getCheckedKeys()
                const halfCheckedMenus = this.$refs.menuTree.getHalfCheckedKeys()
                const allMenus = [...checkedMenus, ...halfCheckedMenus]

                const params = {
                    id: this.currentRole.id,
                    menu: allMenus
                }

                const res = await apiPermissionSave(params)
                if (res.code === 200) {
                    this.$message.success('权限配置保存成功')
                    // 更新角色列表中的角色信息
                    await this.loadRoles()
                } else {
                    throw new Error(res.message || '保存失败')
                }
            } catch (error) {
                this.$message.error(error.message || '保存权限配置失败')
            } finally {
                this.saving = false
            }
        },

        // 重置权限配置
        async resetPermissions() {
            if (!this.currentRole.id) return
            
            try {
                await this.$confirm('确定要重置当前角色的权限配置吗？', '确认重置', {
                    type: 'warning'
                })
                
                // 重新加载角色的权限配置
                await this.loadRoleMenus(this.currentRole.id)
                this.$message.success('权限配置已重置')
            } catch {
                // 用户取消操作
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.authority-manage {
    padding: 20px;
    background: #f5f5f5;
    min-height: calc(100vh - 60px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);

    .header-left {
        h2 {
            margin: 0 0 5px 0;
            color: #333;
            font-size: 24px;
        }
        
        .header-desc {
            margin: 0;
            color: #666;
            font-size: 14px;
        }
    }

    .header-right {
        .el-button {
            margin-left: 10px;
        }
    }
}

.authority-content {
    display: grid;
    grid-template-columns: 350px 1fr;
    gap: 20px;
    align-items: start;
}

.role-selection-card,
.current-role-card,
.menu-permissions-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    overflow: hidden;

    .card-header {
        padding: 16px 20px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
            margin: 0;
            font-size: 16px;
            color: #333;
        }

        .role-count {
            color: #666;
            font-size: 12px;
        }

        .header-actions {
            .el-button {
                margin-left: 8px;
            }
        }
    }

    .card-body {
        padding: 20px;
    }
}

.role-list {
    max-height: 400px;
    overflow-y: auto;
}

.role-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
        border-color: #409eff;
        background: #f0f8ff;
    }

    &.active {
        border-color: #409eff;
        background: #e8f3ff;
    }

    .role-info {
        flex: 1;

        .role-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
        }

        .role-desc {
            font-size: 12px;
            color: #666;
        }
    }
}

.permissions-config {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.role-detail {
    display: flex;
    align-items: center;

    .role-avatar {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background: #f0f8ff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        font-size: 24px;
    }

    .role-detail-info {
        flex: 1;

        h4 {
            margin: 0 0 4px 0;
            color: #333;
        }

        p {
            margin: 0 0 8px 0;
            color: #666;
            font-size: 14px;
        }

        .role-meta {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: #999;
        }
    }
}

.menu-tree {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 8px;
    max-height: 400px;
    overflow-y: auto;
}

.menu-node {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 8px;

    .menu-name {
        font-weight: 500;
    }

    .menu-path {
        background: #f0f0f0;
        color: #666;
    }
}

.empty-state {
    grid-column: span 2;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);

    .empty-content {
        text-align: center;

        .empty-icon {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        h3 {
            margin: 0 0 8px 0;
            color: #333;
        }

        p {
            margin: 0;
            color: #666;
            font-size: 14px;
        }
    }
}

// 响应式设计
@media (max-width: 1200px) {
    .authority-content {
        grid-template-columns: 1fr;
    }
    
    .empty-state {
        grid-column: span 1;
    }
}
</style>
